// src/components/Permission/AdvancedPermissionControl.jsx
import React, { useState } from 'react';
import {
    Table, Card, Button, Space,
    Switch, Tag, Modal, Form,
    Input, Select, message
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LockOutlined
} from '@ant-design/icons';

const { Option } = Select;

const AdvancedPermissionControl = () => {
    const [permissions, setPermissions] = useState([
        {
            id: 1,
            resource: '用户管理',
            resourceKey: 'user-management',
            actions: {
                create: true,
                read: true,
                update: true,
                delete: true,
                export: false
            },
            roles: ['管理员', '人事专员']
        },
        {
            id: 2,
            resource: '数据源管理',
            resourceKey: 'data-source',
            actions: {
                create: true,
                read: true,
                update: false,
                delete: false,
                export: true
            },
            roles: ['管理员', '数据分析师']
        },
        {
            id: 3,
            resource: '内容分发',
            resourceKey: 'content-distribution',
            actions: {
                create: false,
                read: true,
                update: false,
                delete: false,
                export: false
            },
            roles: ['全体员工']
        }
    ]);

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingPermission, setEditingPermission] = useState(null);
    const [form] = Form.useForm();

    const resources = [
        { label: '用户管理', value: 'user-management' },
        { label: '部门管理', value: 'department-management' },
        { label: '角色管理', value: 'role-management' },
        { label: '数据源管理', value: 'data-source' },
        { label: '内容分发', value: 'content-distribution' },
        { label: '系统运维', value: 'system-operations' },
        { label: '元数据驱动', value: 'metadata-driven' }
    ];

    const roles = ['管理员', '人事专员', '数据分析师', '财务专员', '全体员工'];

    const actions = [
        { key: 'create', label: '创建' },
        { key: 'read', label: '读取' },
        { key: 'update', label: '更新' },
        { key: 'delete', label: '删除' },
        { key: 'export', label: '导出' }
    ];

    const handleAddPermission = () => {
        setEditingPermission(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const handleEditPermission = (record) => {
        setEditingPermission(record);
        form.setFieldsValue({
            resource: record.resource,
            resourceKey: record.resourceKey,
            roles: record.roles,
            ...record.actions
        });
        setIsModalVisible(true);
    };

    const handleDeletePermission = (id) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个权限配置吗？',
            onOk: () => {
                setPermissions(permissions.filter(p => p.id !== id));
                message.success('删除成功');
            }
        });
    };

    const handleSavePermission = () => {
        form.validateFields().then(values => {
            const permissionData = {
                resource: values.resource,
                resourceKey: values.resourceKey,
                actions: {
                    create: values.create || false,
                    read: values.read || false,
                    update: values.update || false,
                    delete: values.delete || false,
                    export: values.export || false
                },
                roles: values.roles || []
            };

            if (editingPermission) {
                // 更新权限
                setPermissions(permissions.map(p =>
                    p.id === editingPermission.id
                        ? { ...permissionData, id: editingPermission.id }
                        : p
                ));
                message.success('权限更新成功');
            } else {
                // 添加权限
                setPermissions([
                    ...permissions,
                    { ...permissionData, id: Date.now() }
                ]);
                message.success('权限添加成功');
            }

            setIsModalVisible(false);
        });
    };

    const columns = [
        {
            title: '资源',
            dataIndex: 'resource',
            key: 'resource',
            render: (text, record) => (
                <Space>
                    <LockOutlined />
                    {text}
                </Space>
            )
        },
        ...actions.map(action => ({
            title: action.label,
            dataIndex: ['actions', action.key],
            key: action.key,
            render: (text) => (
                <Switch
                    checked={text}
                    size="small"
                    disabled
                />
            )
        })),
        {
            title: '角色',
            dataIndex: 'roles',
            key: 'roles',
            render: (roles) => (
                <Space wrap>
                    {roles.map(role => (
                        <Tag key={role}>{role}</Tag>
                    ))}
                </Space>
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEditPermission(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeletePermission(record.id)}
                        danger
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    return (
        <div className="advanced-permission-control">
            <Card
                title="高级权限控制"
                extra={
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleAddPermission}
                    >
                        添加权限
                    </Button>
                }
            >
                <Table
                    dataSource={permissions}
                    columns={columns}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                />
            </Card>

            <Modal
                title={editingPermission ? "编辑权限" : "添加权限"}
                open={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                onOk={handleSavePermission}
                width={600}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="resource"
                        label="资源名称"
                        rules={[{ required: true, message: '请输入资源名称' }]}
                    >
                        <Input placeholder="例如：用户管理" />
                    </Form.Item>

                    <Form.Item
                        name="resourceKey"
                        label="资源标识"
                        rules={[{ required: true, message: '请选择资源标识' }]}
                    >
                        <Select placeholder="请选择资源">
                            {resources.map(resource => (
                                <Option key={resource.value} value={resource.value}>
                                    {resource.label}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item label="操作权限">
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
                            {actions.map(action => (
                                <Form.Item
                                    key={action.key}
                                    name={action.key}
                                    valuePropName="checked"
                                    noStyle
                                >
                                    <Switch checkedChildren={action.label} unCheckedChildren={action.label} />
                                </Form.Item>
                            ))}
                        </div>
                    </Form.Item>

                    <Form.Item
                        name="roles"
                        label="适用角色"
                    >
                        <Select
                            mode="multiple"
                            placeholder="请选择适用角色"
                            options={roles.map(role => ({ label: role, value: role }))}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default AdvancedPermissionControl;
